import Koa, { Context } from "koa";
import { router } from "./router";
import koaBody from "koa-bodyparser";
import { errorHandler } from "./middleware/errorHandler";
import { buildTaskResultService } from "./service/BuildTaskResultService";
import { buildTaskService } from "./service/BuildTaskService";
import { reqLogger } from "./middleware/reqLogger";
import { taskScheduler } from "./factory/TaskScheduler";
import { logger } from "./log";
import { initWebSocket } from "./ws";

export async function initServer() {
  // 初始化本地数据服务
  await Promise.all([buildTaskResultService.init(), buildTaskService.init()]);
  // 初始化app
  const app = new Koa();
  app
    .use(reqLogger())
    .use(errorHandler())
    .use(koaBody())
    .use(router.routes())
    .use(router.allowedMethods());
  const server = app.listen(9527, () => {
    logger.info("--- Http server listening at 9527 ---");
    // 检查是否有可运行的任务
    taskScheduler.notify();
  });

  // 绑定websocket
  initWebSocket(server);
}
